#include <QtGui>
#include "qtlotto.h"
//#include <QDebug>

QtLotto::QtLotto(QWidget *parent)
    : QMainWindow(parent)
{
    QString title(tr("Qt Lotto - "));
    title.append(APP_VERSION);
    setWindowTitle(title);
    setWindowIcon(QIcon(":/icon.jpg"));
    setFixedSize(490,400);
    QPushButton *exitButton = new QPushButton(tr("Exit"), this);
    sorsolasButton = new QPushButton(tr("Lottery"), this);
    QPushButton *clearButton = new QPushButton(tr("Clear"), this);
    otosigCB = new QCheckBox(tr("Until five hits"), this);
    huzasokSB = new QSpinBox(this);
    statWidget = new QWidget(this);
    QLabel *statLabel = new QLabel(tr("Lottery statistics:"));
    QLabel *huzastLabel = new QLabel(tr("Number of draws:"));
    QLabel *egyestLabel = new QLabel(tr("One"));
    QLabel *kettestLabel = new QLabel(tr("Two"));
    QLabel *harmastLabel = new QLabel(tr("Three"));
    QLabel *negyestLabel = new QLabel(tr("Four"));
    QLabel *otostLabel = new QLabel(tr("Five"));
    huzasnLabel = new QLabel("0");
    egyesnLabel = new QLabel("0");
    kettesnLabel = new QLabel("0");
    harmasnLabel = new QLabel("0");
    negyesnLabel = new QLabel("0");
    otosnLabel = new QLabel("0");
    statlistaButton = new QPushButton(tr("Listings"), this);
    statlistaButton->setFlat(true);
    statlistaButton->move(340, 270);
    statlistaButton->setFixedSize(80, 20);
    QPalette pal = statlistaButton->palette();
    pal.setColor(QPalette::ButtonText, QColor(Qt::blue));
    statlistaButton->setPalette(pal);
    statlistaButton->hide();
    QGridLayout *statLayout = new QGridLayout;
    statWidget->setFixedSize(320, 80);
    statWidget->move(80, 255);
//    statWidget->setAutoFillBackground(true);
    statLayout->addWidget(statLabel, 0, 0, 1, 5, Qt::AlignCenter);
    statLayout->addWidget(huzastLabel, 1, 0, 1, 3, Qt::AlignRight);
    statLayout->addWidget(huzasnLabel, 1, 3, Qt::AlignLeft);
    statLayout->addWidget(egyestLabel, 2, 0, Qt::AlignCenter);
    statLayout->addWidget(kettestLabel, 2, 1, Qt::AlignCenter);
    statLayout->addWidget(harmastLabel, 2, 2, Qt::AlignCenter);
    statLayout->addWidget(negyestLabel, 2, 3, Qt::AlignCenter);
    statLayout->addWidget(otostLabel, 2, 4, Qt::AlignCenter);
    statLayout->addWidget(egyesnLabel, 3, 0, Qt::AlignCenter);
    statLayout->addWidget(kettesnLabel, 3, 1, Qt::AlignCenter);
    statLayout->addWidget(harmasnLabel, 3, 2, Qt::AlignCenter);
    statLayout->addWidget(negyesnLabel, 3, 3, Qt::AlignCenter);
    statLayout->addWidget(otosnLabel, 3, 4, Qt::AlignCenter);
    statWidget->setLayout(statLayout);
    statWidget->hide();
    exitButton->move(400,350);
    exitButton->setFixedSize(60,30);
    exitButton->show();
    sorsolasButton->move(240,350);
    sorsolasButton->setFixedSize(60,30);
    sorsolasButton->show();
    clearButton->move(320,350);
    clearButton->setFixedSize(60,30);
    clearButton->show();
    otosigCB->move(30, 350);
    otosigCB->setEnabled(false);
    otosigCB->show();
    huzasokSB->move(130, 350);
    huzasokSB->setFixedSize(80, 30);
    huzasokSB->setMinimum(1);
    huzasokSB->setMaximum(99999999);
    huzasokSB->setValue(1);
    huzasokSB->setToolTip(tr("to set the number of pulling"));
//    huzasokSB->setEnabled(false);
    huzasokSB->show();
    createMenus();
//    new QShortcut(Qt::Key_Escape, this, SLOT(close()));
    connect(sorsolasButton, SIGNAL(clicked()), this, SLOT(sorsolasExec()));
    connect(exitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(clearButton, SIGNAL(clicked()), this, SLOT(clearExec()));
    connect(otosigCB, SIGNAL(clicked()), this, SLOT(otosigChanged()));
    connect(statlistaButton, SIGNAL(clicked()), this, SLOT(ShowNyeroLista()));
    tegla.setCoords(20, 60, 470, 240);
    runLongProcess = false;
}

QtLotto::~QtLotto()
{

}

void QtLotto::createMenus()
{
    QAction *exitAct = new QAction(tr("E&xit"), this);
    QAction *aboutqtAct = new QAction(tr("About Qt"), this);
    QAction *showaboutAct = new QAction(tr("About QtLotto"), this);
    QAction *helpAct = new QAction(tr("Manual"), this);
    QAction *settingsAct = new QAction(tr("&Settings"), this);
    QMenu *fileMenu = menuBar()->addMenu(tr("&Menu"));
    QMenu *helpMenu = menuBar()->addMenu(tr("Help"));
    fileMenu->addAction(settingsAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);
    helpMenu->addAction(helpAct);
    helpMenu->addSeparator();
    helpMenu->addAction(aboutqtAct);
    helpMenu->addAction(showaboutAct);
    helpAct->setShortcut(Qt::Key_F1);
    settingsAct->setShortcut(Qt::Key_F2);
    exitAct->setShortcut(Qt::Key_Escape);
    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
    connect(aboutqtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(showaboutAct, SIGNAL(triggered()), this, SLOT(about()));
}

void QtLotto::about()
{
    QString abouttext(tr("This is a free, open-source lottery simulator program, developed in Qt.<br>"));
    abouttext.append(tr("The GPL license under the terms of use.<br>"));
    abouttext.append(tr("<hr>Author: Gyula Blanka <address>&lt;gyula@bsth.hu&gt;</address><br>"));
    abouttext.append(tr("<a href=http://qtlotto.googlecode.com>http://qtlotto.googlecode.com</a>"));
    QMessageBox::about(this, tr("About QtLotto"), abouttext);
}

void QtLotto::paintEvent(QPaintEvent *)
{
//    Q_UNUSED(event);
    QPainter painter(this);
//    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(rect(), QColor(255, 235, 195));
//    painter.drawPixmap(rect(), QPixmap(":/background.jpg"));
    painter.setPen(Qt::blue);
    painter.setBrush(Qt::NoBrush);
    painter.setFont(QFont("Arial", 10));
    painter.drawText(0,20, width(), 30, Qt::AlignCenter, tr("Qt lotto program"));
    painter.drawRoundedRect(tegla, 10, 10);
    QLine vonal(tegla.x()+30, tegla.y(), tegla.x()+30, tegla.y()+180);
    for (int i=1; i<15; i++)
    {
        painter.drawLine(vonal);
        vonal.translate(30,0);
    }
    vonal.setLine(tegla.x(), tegla.y()+30, tegla.x()+450, tegla.y()+30);
    for (int i=1; i<6; i++)
    {
        painter.drawLine(vonal);
        vonal.translate(0,30);
    }
    painter.setFont(QFont("Arial", 8));
    for (int p=0; p<6; p++)
    {
        for (int i=0; i<15; i++)
        {
            int szam=p*15+i+1;
            if (jeloltek.contains(szam))
                painter.setPen(Qt::red);
            else
                painter.setPen((Qt::blue));
            QPoint szamsarok(tegla.x()+i*30, tegla.y()+p*30);
            QRect szamblokk(szamsarok, QSize(30,30));
            painter.drawText(szamblokk, Qt::AlignCenter, QString::number(szam));
        }
    }
    if (nyeroszamok.count())
    {
        painter.setPen(Qt::red);
        for (int p=0; p<6; p++)
            for (int i=0; i<15; i++)
            {
                QPoint szamkozep(tegla.x()+i*30+15, tegla.y()+p*30+15);
                if (nyeroszamok.contains(p*15+i+1))
                    painter.drawEllipse(szamkozep, 10, 10);
            }
        if (huzasokSB->value() == 1)
        {
            painter.setFont(QFont("Arial", 14));
            QString szamsor(tr("Winning numbers: "));
            int talalat=0;
            for (int i=0; i<5; i++)
            {
                if (jeloltek.contains(nyeroszamok.at(i)))
                    talalat++;
                szamsor.append(QString::number(nyeroszamok.at(i)));
                if (i!=4)
                    szamsor.append(", ");
            }
            painter.drawText(0,180,this->width(),200,Qt::AlignCenter, szamsor);
            if (jeloltek.count() > 0)
                painter.drawText(0,200,this->width(), 220, Qt::AlignCenter, tr("Hits: ") + QString::number(talalat));
        }
    }
    painter.end();

}

void QtLotto::ShowNyeroLista()
{
    QString addstring;
    QTextEdit *showlista = new QTextEdit;
    new QShortcut(Qt::Key_Escape, showlista, SLOT(close()));
    showlista->setWindowTitle(tr("Winning numbers list"));
    showlista->setReadOnly(true);
    int huzasszam=nyerolista.count()/5;
    for (int i=0; i<huzasszam; i++)
    {
        addstring.clear();
        for (int w=0; w<5; w++)
        {
            int t=i*5+w;
            addstring.append(QString::number(nyerolista.at(t)));
            if (w<4)
                addstring.append(", ");
        }
        showlista->append(addstring);
    }
    showlista->show();
}

void QtLotto::Randomize(QList<int> *rn)
{
    int i=0, p=0;
    while (i<5)
    {
        p=qrand()%90+1;
        if (!rn->contains(p))
        {
            rn->append(p);
            i++;
        }
    }
//    rn->clear();
//    *rn << 1 << 2 << 3 << 4 << 5;
}

void QtLotto::hosszusorsolas()
{
    unsigned int counter(0), maxlistsize=100;
    int tal=0, cnt2disp=0;
    QList<int> nyerosz;
    QVector<int> talalatok(5);
    bool tmphuzasokSB=false;
    nyerolista.clear();
    talalatok.fill(0);
    egyesnLabel->setText("0");
    kettesnLabel->setText("0");
    harmasnLabel->setText("0");
    negyesnLabel->setText("0");
    otosnLabel->setText("0");
    runLongProcess = true;
    if (jeloltek.count())
        statWidget->show();
    else if (huzasokSB->value() > (int ) maxlistsize)
    {
        QString errmaxvalstr(tr("A number of drag in this mode can be up to %n !", "", maxlistsize));
        QMessageBox::information(this, tr("Value is not allowed"), errmaxvalstr);
        runLongProcess = false;
    }
    sorsolasButton->setEnabled(false);
    otosigCB->setEnabled(false);
    if (huzasokSB->isEnabled())
    {
        tmphuzasokSB = true;
        huzasokSB->setEnabled(false);
    }
    statlistaButton->hide();
    while (runLongProcess)
    {
        tal=0;
        nyerosz.clear();
        ++counter;
        Randomize(&nyerosz);
        if (counter <= maxlistsize)
            nyerolista.append(nyerosz);
        for (int i=0; i<5; i++)
            if (jeloltek.contains(nyerosz.at(i)))
                tal++;
//        if (tal)
//            talalatok[tal-1]++;
        switch (tal)
        {
        case 1:
            ++talalatok[0];
            egyesnLabel->setText(QString::number(talalatok.at(0)));
            break;
        case 2:
            ++talalatok[1];
            kettesnLabel->setText(QString::number(talalatok.at(1)));
            break;
        case 3:
            ++talalatok[2];
            harmasnLabel->setText(QString::number(talalatok.at(2)));
            break;
        case 4:
            ++talalatok[3];
            negyesnLabel->setText(QString::number(talalatok.at(3)));
            break;
        case 5:
            ++talalatok[4];
            otosnLabel->setText(QString::number(talalatok.at(4)));
            break;
        }
        huzasnLabel->setText(QString::number(counter));
        ++cnt2disp;
        if (cnt2disp == 1000)
        {
            QApplication::processEvents();
            cnt2disp = 0;
        }
//        qDebug() <<nyerosz.at(0) << "," <<nyerosz.at(1) << "," <<nyerosz.at(2) << "," <<nyerosz.at(3) << "," <<nyerosz.at(4);
        if (counter == (unsigned int) huzasokSB->value() && ! otosigCB->isChecked())
            runLongProcess = false;
        if (otosigCB->isChecked() && tal == 5)
            runLongProcess = false;
//        QMessageBox::information(this, "huu", QString::number(tal));
    }
    sorsolasButton->setEnabled(true);
    if (jeloltek.count())
        otosigCB->setEnabled(true); //not pressed clear button (clearExec)
    if (tmphuzasokSB)
        huzasokSB->setEnabled(true);
    if (counter <= maxlistsize && jeloltek.count())
        statlistaButton->show();
    else if (counter != 0 && jeloltek.count() == 0 && huzasokSB->value() > 1)
        ShowNyeroLista();
}

void QtLotto::sorsolasExec()
{
    nyeroszamok.clear();
    update();
    if (otosigCB->isChecked() || huzasokSB->value() > 1)
        hosszusorsolas();
    else
        Randomize(&nyeroszamok);
    update();
}

void QtLotto::otosigChanged(void)
{
    if (otosigCB->isChecked())
        huzasokSB->setEnabled(false);
    else
        huzasokSB->setEnabled(true);
}

void QtLotto::clearExec()
{
    jeloltek.clear();
    nyeroszamok.clear();
    runLongProcess = false;
    otosigCB->setEnabled(false);
    otosigCB->setChecked(false);
    huzasokSB->setEnabled(true);
    huzasokSB->setValue(1);
    statWidget->hide();
    statlistaButton->hide();
    update();
}

void QtLotto::mousePressEvent(QMouseEvent *event)
{
    int katt;
    if (event->x() < tegla.x() || event->x() > tegla.right() || event->y() < tegla.y() || event->y() > tegla.bottom())
        return;
//    x=(event->x()-tegla.x())/30+1;
//    y=(event->y()-tegla.y())/30+1;
    katt=((event->x()-tegla.x())/30+1) + ((event->y()-tegla.y())/30)*15;
    if (jeloltek.contains(katt))
    {
        jeloltek.removeOne(katt);
        otosigCB->setEnabled(false);
//        huzasokSB->setEnabled(false);
    }
    else if (jeloltek.count() < 5)
        jeloltek.append(katt);
//    QMessageBox::information(this, "Mouse event", QString::number(katt));
    nyeroszamok.clear();
    if (jeloltek.count() == 5)
    {
        otosigCB->setEnabled(true);
//        huzasokSB->setEnabled(true);
        otosigChanged();
    }
    statWidget->hide();
    statlistaButton->hide();
    update();
}

void QtLotto::closeEvent(QCloseEvent *event)
{
    if (nyeroszamok.count() || runLongProcess)
    {
        QMessageBox mess;
        mess.setWindowTitle(tr("Exit"));
        mess.setText(tr("Are you sure you want to exit?"));
        mess.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        int ret(mess.exec());
        if (ret == QMessageBox::Yes)
        {
            runLongProcess = false;
            event->accept();
        }
        else
            event->ignore();
    }
    else
        event->accept();
}
